package tmall.framework.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tmall.framework.service.IdService;
import tmall.framework.service.impl.AutowiredIdConfigurerIgnoreParents;
import tmall.framework.service.impl.SegmentsServiceImpl;
import tmall.framework.utils.SpringContextUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
public class IdFactoryConfigurer {
    @Resource
    private ConfigurableListableBeanFactory beanFactory;
    @Resource
    private SpringContextUtil springContextUtil;
    
    private AutowiredIdConfigurerIgnoreParents autowiredIdConfigurerIgnoreParents;


    @Bean
    public AutowiredIdConfigurerIgnoreParents autowiredIdConfigurerIgnoreParents() {
        autowiredIdConfigurerIgnoreParents = new AutowiredIdConfigurerIgnoreParents(beanFactory);
        return autowiredIdConfigurerIgnoreParents;
    }

    @Bean
    public IdService idService(@Value("#{@autowiredIdConfigurerIgnoreParents.getIdService()}") List<IdService> idServiceList) {
        if (idServiceList == null || idServiceList.size() == 0) {
            return new SegmentsServiceImpl();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("start using id generator " + idServiceList.get(0).getClass());
            }
            return idServiceList.get(0);
        }
    }

}
